<!--
日期选择器
v1.0.0 前后年的数据
-->

<template>
  <div class="sh-date">
    <sh-picker :id="c_id" v-model="c_val"
               @scroll="pickerScroll"
               :is_show.sync="c_show"
               :data="picker_data">
    </sh-picker>
  </div>
</template>
<style>
  .sh-date {
    position: fixed;
    z-index: 10000;
  }
</style>
<script>
  export default {
    name: 'sh-date',
    props: {
      id: String,
      value: String,
      last_years: Number,//前几年
      next_years: Number,//后几年
      show: Boolean,
    },
    data() {
      return {
        c_id: "",
        c_show: false,
        c_val: [],
        c_last_years: 0,
        c_next_years: 0,
        show_picker: true,
        picker_data: [],
      }
    },
    beforeMount: function () {

    },
    mounted: function () {
      this.c_id = this.id || "sh-date-picker";
      this.c_show = this.show;
      this.c_val = this.value.split("-");
      this.c_last_years = this.last_years == undefined ? 3 : this.last_years;
      this.c_next_years = this.next_years == undefined ? 3 : this.next_years;
      this.picker_data = [[this.c_val[0]], [this.c_val[1]], [this.c_val[2]]];
      this.initPickerData();
    },
    methods: {
      initPickerData() {
        let cur = new Date();
        cur.setSeconds(0);
        cur.setMinutes(0);
        cur.setHours(0);
        let years = [];
        for (let year = cur.getFullYear() - this.c_last_years;
             year <= cur.getFullYear() + this.c_next_years;
             year++) {
//          console.log(year);
          years.push(year);
        }
        let months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

        let max_day = this.getMonthMaxDay(cur);
        let days = [];
        for (let i = 1; i <= max_day; i++) {
          days.push(i);
        }
        this.picker_data = [years, months, days];
      },
      pickerScroll(val) {
//        console.log(val);
        let max_day = this.getMonthMaxDay(`${val[0]}/${val[1]}/1`);
        if (this.c_val[2] > max_day) {
          this.c_val.splice(2, 1, max_day);
        }
        let days = [];
        for (let i = 1; i <= max_day; i++) {
          days.push(i);
        }
        this.picker_data[2] = days;

        this.$emit("input", `${this.c_val[0]}-${this.c_val[1]}-${this.c_val[2]}`)
      },
      // 获取当月最大天数
      getMonthMaxDay(date_val) {
        let date = new Date(date_val);
        date.setDate(1);
        date.setMonth(date.getMonth() + 1);
        date.setDate(date.getDate() - 1);
        return date.getDate();
      }
    },
    watch: {
      show() {
        this.c_show = this.show;
      },
      c_show() {
        this.$emit("update:show", this.c_show);
      }
    },
  };
</script>
